package org.kojo.tdrm.servlet.ctrl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.ant.util.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kojo.tdrm.entity.Task;
import org.kojo.tdrm.entity.User;
import org.kojo.tdrm.service.TaskAppService;
import org.kojo.tdrm.utils.JSONUtils;
import org.kojo.tdrm.valbean.TaskVal;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class TaskAppController extends BaseController {
	private static Logger log = Logger.getLogger(TaskAppController.class.getName());
	private TaskAppService taskAppService;
	private String DATE_FORMAT = "dd/MM/yy hh:mm";
	/**
	 * 
	 */
	private static final long serialVersionUID = 3244815521080790387L;

	public TaskAppController() {
		taskAppService = new TaskAppService();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if ("taskSize".endsWith(action)) {
			int taskSize = taskAppService.countTask(getUserId());
			log.fine(getUserId() + ":taskSize=" + taskSize);
			JSONObject o = new JSONObject();
			try {
				o.put("taskSize", taskSize);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			setJsonResp(o.toString());
			return;
		}
		if ("searchTaskSize".endsWith(action)) {
			String searchInput = req.getParameter("searchInput");
			int taskSize = taskAppService.countBySearchTask(getUserId(), searchInput);
			log.fine(getUserId() + ":searchTaskSize=" + taskSize);
			JSONObject o = new JSONObject();
			try {
				o.put("taskSize", taskSize);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			setJsonResp(o.toString());
			return;
		}
		if ("listRange".equals(action)) {
			long fromIncl = Long.parseLong(req.getParameter("fromIncl"));
			long toExcl = Long.parseLong(req.getParameter("toExcl"));
			List<Task> lsTask = taskAppService.listTaskByRange(getUserId(),
					fromIncl, toExcl);
			JSONArray j = JSONUtils.jsonArrayParser(lsTask);
			setJsonResp(j.toString());
			return;
		}
		if ("listAll".equals(action)) {
			List<Task> lsTask = taskAppService.listTaskByUserId(getUserId());
			JSONArray j = JSONUtils.jsonArrayParser(lsTask);
			setJsonResp(j.toString());
			return;
		}
		if("search".equals(action)){
			long fromIncl = Long.parseLong(req.getParameter("fromIncl"));
			long toExcl = Long.parseLong(req.getParameter("toExcl"));
			String search = req.getParameter("search");
			List<Task> lsTask = taskAppService.searchTask(getUserId(), search, fromIncl, toExcl);
			JSONArray j = JSONUtils.jsonArrayParser(lsTask);
			setJsonResp(j.toString());
			return;
		}
		if("findtask".equals(action)){
			long taskId = Long.parseLong(req.getParameter("taskid"));
			Task t = taskAppService.findTask(getUserId(), taskId);
			TaskVal tv = new TaskVal(t);
			JSONObject j = new JSONObject(tv);
			setJsonResp(j.toString());
			log.fine("login["+super.getUserId()+"] findtask -> "+j.toString());
			return;
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String strId = req.getParameter("id");
		String name = req.getParameter("name");
		String dueDateStr = req.getParameter("dueDate");
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
		Date dueDate = null;
		try {
			dueDate = sdf.parse(dueDateStr);
		} catch (ParseException e) {
			throw new ServletException("input date:"+dueDateStr+" parse error.");
		}
		String note = req.getParameter("note");
		Integer priority = Integer.parseInt(req.getParameter("priority"));
		Integer repeatType = Integer.parseInt(req.getParameter("repeatType"));
		Integer repeatEvery = 0;
		if(repeatType!=Task.ONE_TIME){
			repeatEvery = Integer.parseInt(req.getParameter("repeatEvery"));
		}
		
		
		if(strId==null||"".equals(strId)){
			//new
			Task t = new Task(name, dueDate, note);
			t.setPriority(priority);
			t.setState(TaskAppService.ONGOING);
			t.setRepeatType(repeatType);
			t.setRepeatEvery(repeatEvery);
			// invoke service
			taskAppService.createTask(getUserId(), t);
			log.fine("create=" + t.toString()+", name="+t.getName());
			JSONObject o = new JSONObject(t);
			setJsonResp(o.toString());
		} else {
			//save
			long id = Long.parseLong(strId);
			Task t = taskAppService.findTask(getUserId(), id);
			t.setName(name);
			t.setDueDate(dueDate);
			t.setNote(note);
			t.setPriority(priority);
			t.setRepeatType(repeatType);
			t.setRepeatEvery(repeatEvery);
			log.fine("save="+t.toString()+", name="+t.getName());
			taskAppService.saveTask(t);
			//no resp
		}
		
		
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if ("delete".equals(action)) {
			String id = req.getParameter("id");
			log.fine("login["+super.getUserId()+"] delete id=" + id);
			taskAppService.deleteTask(getUserId(), Long.parseLong(id));
			//return
			JSONObject j = new JSONObject();
			try {
				j.put("actionResult", "success");
				j.put("action", action);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			setJsonResp(j.toString());
			return;
		}
		if ("clearcomplete".equals(action)) {
			log.fine("login["+super.getUserId()+"] Clear complete task for user:" + getUserId());
			taskAppService.clearCompleteTask(getUserId());
			//return
			JSONObject j = new JSONObject();
			try {
				j.put("actionResult", "success");
				j.put("action", action);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			setJsonResp(j.toString());
			return;
		}
		resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED,"action '"+action+"' not implemented");
		
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		long taskId = Long.parseLong(req.getParameter("id"));
		String state = req.getParameter("state");
		//
		log.fine("login["+super.getUserId()+"] change task state =" + state);
		taskAppService.updateTaskState(getUserId(), taskId, state);
		JSONObject j = new JSONObject();
		try {
			j.put("actionResult", "success");
			j.put("taskId", taskId);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		setJsonResp(j.toString());
	}

}
